﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using uPLibrary.Networking.M2Mqtt;
using uPLibrary.Networking.M2Mqtt.Messages;

namespace MQTTDemo
{
    class Program
    {

        static M2MClient client = new M2MClient("mqtt.nireniot.com");

        static void Main(string[] args)
        {
            client.SetReceMsgDelegate(GetReceMsg);
            Thread thread = new Thread(SendCmdThread);
            thread.IsBackground = true;
            thread.Start();

            Thread printfThread = new Thread(PrintfOnlineDeviceMacThread);
            printfThread.IsBackground = true;
            printfThread.Start();            


            while (true)
            {
                Console.WriteLine("结束请输入 q ");
                string readKey = Console.ReadLine();
                if (readKey == "q")
                    break;
            }
        }

        static void SendCmdThread() { 
            while (true)
            {
                string mac = "11:22:33:44:55:66";
                string atCmd = "AT+STACH1=1\r\n";
                Console.WriteLine("向设备<" + mac + ">发送指令<" + atCmd + ">");
                client.SendMsg(mac, atCmd);
                Thread.Sleep(3000);
            }
        }

        static void PrintfOnlineDeviceMacThread() { 
            while(true)
            {
                Thread.Sleep(5000) ;
                List<string> macs = client.GetOnlineDeviceList(true);
                foreach(string mac in macs)
                {
                    Console.WriteLine("在线设备->" + mac);
                }
            }
        }

        static void GetReceMsg(string mac,string receMsg) {
            Console.WriteLine("接收到设备<" + mac + ">的指令为<" + receMsg + ">");
        }
    }
}
